<?php
//  +----------------------------------------------------------------------
//  | Copyright (c) 2015-2025 http://www.hdphp.cn All rights reserved.
//  | Licensed ( http://www.hdphp.cn/licenses/ )
//  | Author: Jack <sophia2152@qq.com>
//  | 官方网址: http://www.hdphp.cn
//  | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//  | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//  +----------------------------------------------------------------------

namespace app\services\short;

use app\model\short\Short;
use app\services\BaseServices;
use hdphp\exceptions\AdminException;
use hdphp\services\CacheService;
use think\exception\ValidateException;

class ShortServices extends BaseServices
{

    protected $openUrl = 'https://mp.hnzxyy.com/short/';

    /**
     * 构造方法
     * @param Short $model
     */
    public function __construct(Short $model)
    {
        $this->model = $model;
    }

    /**
     * Notes：getSetShort
     * User：Jack
     * DateTime：2022/11/1 15:09
     * @param string $url
     * @return false|string
     */
    public function getSetShort(string $url)
    {
        if ($url == '') throw new AdminException('请输入URL');
        if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
            throw new AdminException('请输入正确的URL');
        }
        // 生成KEY
        $key_str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        $key = substr(str_shuffle($key_str), mt_rand(0, strlen($key_str) - 11), 4);
        $data = $this->model->getOne(['url' => $url]);
        if ($data) {
            return $this->openUrl . $data['key'];
        }
        $save['key'] = $key;
        $save['url'] = $url;
        $save['create_time'] = date('Y-m-d H:i:s', time());
        if ($this->model->insert($save)) {
            CacheService::set($key, $url, 0);
            return $this->openUrl . $key;
        } else {
            return false;
        }
    }

    /**
     * Notes：getCheckName
     * User：Jack
     * DateTime：2022/10/31 15:30
     * @param string $name
     * @return mixed
     */
    public function getCheckName(string $name)
    {
        $re = CacheService::get($name);
        if (!$re) {
            $checkData = $this->model->getOne(['key' => $name]);
            if (!$checkData || !$checkData->url) {
                throw new ValidateException('Response is empty data');
            }
            return $checkData['url'];
        }

        return $re;
    }


}